#include "Sprite.h"
#include "Global.h"
#include <gdiplus.h>
Sprite::Sprite(void){}

Sprite::Sprite(LPDIRECT3DTEXTURE9 texture, int width, int height, int count, int spritePerRow){
	_texture		 = texture;
	_width			 = width;
	_height			 = height;
	_count			 = count;
	_spritePerRow	 = spritePerRow;
	_index			 = 0;
	
}

Sprite::~Sprite(void)
{
	_texture->Release();
}

void Sprite::Next()
{
	_index = (_index + _count - 1) % _count;
}
void Sprite::Next(int start, int end){
	
	if (_index < start || _index >= end)
		_index = start;
	else if(_index == start) _index++;
	else if(_index >start && _index < end)
			_index++;
		
}
void Sprite::Reset(){
	_index = 0;
}
void Sprite::Reset(int t){
	_index = t;
}
void Sprite::Render(LPDIRECT3DSURFACE9 target, int x, int y)
{
	RECT srect;
	srect.left = (_index % _spritePerRow)* _width;
	srect.top = (_index / _spritePerRow)* _height;
	srect.right = srect.left + _width ;
	srect.bottom = srect.top + _height;
	Global::_Directx->_spriteHandler->Begin(D3DXSPRITE_ALPHABLEND);

	D3DXVECTOR3 position((float)x, (float)y, 0);

	Global::_Directx->_spriteHandler->Draw(
		_texture,
		&srect,
		NULL,
		&position,
		D3DCOLOR_XRGB(255,255,255));

	Global::_Directx->_spriteHandler->End();
}

void Sprite::Render(LPDIRECT3DSURFACE9 target, int x, int y, int vpx, int vpy)
{
	RECT rect;
	rect.left = (_index % _spritePerRow)* _width;
	rect.top = (_index / _spritePerRow)* _height ;
	rect.right = rect.left + _width ;
	rect.bottom = rect.top + _height;
	Global::_Directx->_spriteHandler->Begin(D3DXSPRITE_ALPHABLEND);

	D3DXVECTOR3 position((float)x, (float)y, 0);

	D3DXMATRIX mt;
	D3DXMatrixIdentity(&mt);
	mt._22 = -1.0f;
	mt._41 = -vpx;
	mt._42 = vpy;

	D3DXVECTOR4 vp_pos;
	D3DXVec3Transform(&vp_pos, &position, &mt);

	D3DXVECTOR3 p(vp_pos.x + ((float)_width/2), vp_pos.y + ((float)_height/2), 0);//Ve tu tam thi no se bi lech ot doan x 
	D3DXVECTOR3 center((float)_width/2, (float)_height/2, 0);

	Global::_Directx->_spriteHandler->Draw(_texture,
		&rect,
		&center,
		&p,
		D3DCOLOR_XRGB(255,255,255));

	Global::_Directx->_spriteHandler->End();
}
void Sprite::Render(int X, int Y, int vpx, int vpy)
{
	RECT srect;

	srect.left = (_index % _spritePerRow)*(_width)+1;
	srect.top = (_index / _spritePerRow)*(_height)+1;
	srect.right = srect.left + _width ;
	srect.bottom = srect.top + _height +1;

	D3DXVECTOR3 position((float)X,(float)Y,0);

	//
	// WORLD TO VIEWPORT TRANSFORM USING MATRIX
	//

	D3DXMATRIX mt;
	D3DXMatrixIdentity(&mt);
	mt._22 = -1.0f;
	mt._41 = -vpx;
	mt._42 = vpy;
	D3DXVECTOR4 vp_pos;
	D3DXVec3Transform(&vp_pos,&position,&mt);
	
	D3DXVECTOR3 p(vp_pos.x,vp_pos.y,0);
	D3DXVECTOR3 center((float)_width/2,(float)_height/2,0);
	
	Global::_Directx->_spriteHandler->Draw(
		_texture,
		&srect,
		&center,
		&p, 
		D3DCOLOR_XRGB(255,255,255)
	);

}